#!/usr/bin/env python
# -*- coding: utf-8 -*-


import os
import sys
import platform
import subprocess

DEFAULT     = "help"
FLEX        = "D:/tools/flex/flex_sdk_4.1"
BASE        = os.path.abspath(os.path.curdir).replace("\\","/")+'/'
FLEX_CONFIG = BASE+"obj/CaelumConfig.xml"
JAVA        = "java"



if FLEX[len(FLEX)-1]!='/' or FLEX[len(FLEX)-1]!='\\':
    FLEX+='/'

if not os.path.exists(FLEX+"bin/mxmlc.exe"):
    print "ERROR: Flex not Found"
    exit(-1)



#import getopt


class Command(object):
    _minspace=15
    
    def __init__(self):
        pass

    def command(self,argv):
        #print " ".join(argv)
        argv=argv[1:]
        for arg in argv:
            if hasattr(self,arg):
                cmd=getattr(self,arg)
                cmd()
        self._exec()
        
    def _exec(self):
        pass

    def help(self):
        "show this help"
        
        list=dir(self)
        result="\nOPTION"
        result+=' '*(self._minspace-len("OPTION"))+"HELP\n"
        for ind in list:
            if ind[0]=="_" or ind=="command" or ind=="execCommand":
                continue
            obj=getattr(self,ind)
            
            doc="unknown"
            if hasattr(obj,"im_func"):
                doc=str(obj.im_func.func_doc)
                result+=""+str(ind)+':'+' '*(self._minspace-len(ind)-1)+doc+"\n"
        if platform.release()=="Vista":
            print "VISTA USER: you need to use: python.exe file.py"

    def execCommand(self,*arg):
        #print "exec: "+' '.join(arg)
        #print ""
        pipe = subprocess.Popen(arg, stdout=subprocess.PIPE,cwd=FLEX)
        ret = pipe.stdout.read()
        return ret


class Caelum(Command,object):
    def __init__(self):
        Command.__init__(self)
    
    def main(self):
        "Build Realease version"
        pass 
    
    def compile(self):
        "Build application"
        arg=[JAVA,"-Xmx384m","-Dsun.io.useCanonCaches=false","-jar"]
        arg+=[FLEX+'lib/mxmlc.jar',"+flexlib="+FLEX+"frameworks/"]
        arg+=['-load-config+='+FLEX_CONFIG,"-verbose-stacktraces=true" ]
        print self.execCommand(*arg)

    def version(self):
        "Get Flex Version"
        print self.execCommand(FLEX+'bin/mxmlc.exe','-version')

    def help(self):
        "Show this help"
        print "\nusage : build.py [options] [flex option]"
        Command.help(self)
        




if __name__ == "__main__":
    build=Caelum()
    arg=sys.argv
    
    if len(arg[1:])==0:
        arg.append(DEFAULT)
    
    build.command(arg)
        
        

